package com.github.livebase.plugins;

import com.github.livebase.log.Logger;
import com.github.livebase.storage.LocalStorage;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * @ClassName PluginContext
 * @description:
 * @author: biao532
 * @create: 2023-12-30 21:59
 * @Version 1.0
 **/
public class PluginContext {
    private String name;
    private File rootDir;
    private LocalStorage storage;
    private PluginFactory factory;
    private int pluginVersion;
    private Logger logger;
    private ClassLoader loader;
    private String configDir;

    public PluginContext(String name, int pluginVersion, File rootDir, String configDir, PluginFactory factory, ClassLoader loader) {
        this.rootDir = rootDir;
        this.name = name;
        this.factory = factory;
        this.pluginVersion = pluginVersion;
        this.loader = loader;
        this.configDir = configDir;
    }
    public File getRootDir() {
        return rootDir;
    }

    public String getName() {
        return name;
    }

    public int getPluginVersion() {
        return pluginVersion;
    }

    public InputStream getResource(String path) throws FileNotFoundException {
        if (path == null) throw new FileNotFoundException("no such path for null");
        File file = new File(getRootDir(), path);
        return new FileInputStream(file);
    }

    public InputStream getConfig(String path) throws FileNotFoundException {
        if (path == null) throw new FileNotFoundException("no such path for null");
        File file = new File(getRootDir(), configDir);
        return new FileInputStream( new File(file, path) );
    }

    public InputStream getResourceIfExist(String... paths) throws FileNotFoundException {
        for (String path : paths) {
            File file = new File(getRootDir(), path);
            if (file.exists()) {
                return getResource(path);
            }
        }
        throw new FileNotFoundException("no such path");
    }

    // 不考虑多线程
    public LocalStorage getStorage() {
        if (storage == null) {
            storage = factory.newStorage(this);
        }
        return storage;
    }

    public ClassLoader getClassLoader() {
        return loader;
    }

    // 不考虑多线程
    public Logger getLogger() {
        if (logger == null) {
            logger = factory.newLogger(this);
        }
        return logger;
    }
}
